﻿using UnityEngine;
using System.Collections;
using UnityEngine.Networking;

public class PlayerMove : NetworkBehaviour {
	public float moveSpeed = 5.0f;
	Vector3 movement;          //移动的方向向量
	Rigidbody playerRigidbody;
	int floorMask;
	float camRayLength = 100f;
	//NetworkTransform networkTransform;
	void Awake()
	{
		//networkTransform= GetComponent<NetworkTransform> ();
		floorMask = LayerMask.GetMask("Floor");
		playerRigidbody = gameObject.GetComponent<Rigidbody>();
	}
	void FixedUpdate()
	{
		if (!isLocalPlayer) {
			return;
		}
		float h = Input.GetAxisRaw("Horizontal");
		float v = Input.GetAxisRaw("Vertical");

		Move(h, v);
		Turning();
		//Animating(h, v);
	}

	void Move(float h, float v)
	{
		movement.Set(h, 0f, v);//固定Y轴为0的方向向量
		movement = transform.position + movement.normalized;
		//movement = movement.normalized * moveSpeed * Time.deltaTime;
		//使用模为1的单位向量，结合deltatime，使移动平滑
		//使用Rididbody类里面的MovePosition（）函数--会让player是在力的作用下移动，与其他刚体会产生接触碰撞
		//playerRigidbody.MovePosition(Vector3.Lerp(transform.position, movement, moveSpeed * Time.deltaTime));
		transform.position = Vector3.Lerp(transform.position, movement, moveSpeed * Time.deltaTime);
	}

	void Turning()
	{
		Ray camRay = Camera.main.ScreenPointToRay(Input.mousePosition);//从相机所在点到鼠标在屏幕上的点的射线
		RaycastHit floorHit;//代表射线被 截断点

		//Raycast（ray，out hitpoint，distance，layermask）函数--是在distance范围内，如果射线ray射中了可被射中层内
		//（layermask代表的层）的物体，则返回true，并且将射中点包含的一系列信息赋给 hitpoint（RaycastHit类型）---一个**结构体**类型
		if(Physics.Raycast(camRay,out floorHit,camRayLength,floorMask))
		{
			Vector3 playerToMouse = floorHit.point - transform.position;
			playerToMouse.y = 0f;

			Quaternion newRotation = Quaternion.LookRotation(playerToMouse);
			playerRigidbody.MoveRotation(newRotation);
		}
	}
}
